package com.shuqi.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.TextView;

import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.FeedBackController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.FeedBacksInfo;
import com.shuqi.model.manager.MyAccountManager;

/**
 * 意见反馈Activity
 * @author yanghuawei
 * 
 */
public class FeedBackActivity extends ActivityBase implements IEventListener, OnClickListener {

    private final int init = 0;
    private final int Commit_Success = 1;
    private final int Commit_error = 2;
    private String message;
    
    private FeedBackController controller;
    private String content; // 提交内容
    private String contact; // 联系方式
    private final int MAX_LENGTH = 250;// 评论可输入文字总数
    private int Rest_Length = MAX_LENGTH;// 评论还可输入文字数
    private TextView feedback_number_text;
    private EditText feedback_content_edit;
    private EditText feedback_contact_edit;
    private FeedBacksInfo feedBacksInfo;
    private ToastDialog mLoginDialog;// 底部提示框
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case Commit_Success:
                    onCommitFinish(true);
                    break;
                case Commit_error:
                    onCommitFinish(false);
                    break;
            }
        };
    };

    /** Activity初始化 */
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (FeedBackController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_FEEDBACK, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_feedback);
        handler.sendEmptyMessage(init);
    }

    @Override
    public void onEvent(int event, Object data) {
        message = null;
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                feedBacksInfo = (FeedBacksInfo) data;
                if(feedBacksInfo != null && "200".equals(feedBacksInfo.getCode())){
                    message = feedBacksInfo.getMessage();
                    handler.sendEmptyMessage(Commit_Success);
                    return;
                }else if(feedBacksInfo != null){
                    message = feedBacksInfo.getMessage();
                }else{
                    message = "提交失败";
                }
                handler.sendEmptyMessage(Commit_error);
                break;
            case EventTypeConstants.EVENT_EXC_APNNOTEXIST:
                message = getResources().getString(R.string.retry_after_connect_network);
                handler.sendEmptyMessage(Commit_error);
                break;
            default:
                message = getResources().getString(R.string.net_error_text);
                handler.sendEmptyMessage(Commit_error);
                break;
        }
    }

    /** 初始化布局 */
    @Override
    public void activityLogicForward() {
        this.feedback_content_edit = (EditText) findViewById(R.id.feedback_content_edit);
        feedback_content_edit.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if (view.getId() == R.id.feedback_content_edit) {
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case MotionEvent.ACTION_UP:
                            view.getParent().requestDisallowInterceptTouchEvent(false);
                            break;
                    }
                }
                return false;
            }
        });

        this.feedback_contact_edit = (EditText) findViewById(R.id.feedback_contact_edit);
        this.feedback_number_text = (TextView) findViewById(R.id.feedback_number_text);
        this.feedback_contact_edit.setSelected(false);
        this.feedback_content_edit.setSelected(true);
        this.findViewById(R.id.feedback_commit_text).setOnClickListener(this);// 点击提交
        this.findViewById(R.id.title_left).setOnClickListener(this);

        // 监听字数变化
        feedback_content_edit.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (Rest_Length >= 0) {
                    Rest_Length = MAX_LENGTH - feedback_content_edit.getText().length();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                feedback_number_text.setText("剩余" + Rest_Length + "" + "字");
            }

            @Override
            public void afterTextChanged(Editable s) {
                feedback_number_text.setText("剩余" + Rest_Length + "" + "字");
            }
        });
        InputFilter inflater = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                if(!isRightFormat(source.toString())){
                   return ""; 
                }
                return source;
            }
        };
        LengthFilter lengthFilter = new LengthFilter(30);
        feedback_contact_edit.setFilters(new InputFilter[]{inflater,lengthFilter});
    }
    
    /***
     * 判断字符串是否由:a-zA-Z0-9._@ 组成
     * @param content
     * @return
     */
    private boolean isRightFormat(String content){
        String string = "^[a-zA-Z0-9_@.]{1,30}$";
        Pattern mPattern = Pattern.compile(string);
        Matcher matcher = mPattern.matcher(content);
        return matcher.matches();
    }
    
    @Override
    public void activityInitData() {}

    /** 点击事件 */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            // 提交内容
            case R.id.feedback_commit_text:
                // 收起键盘
                Util.inputMethodControl(this, false);
                content = feedback_content_edit.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    this.showMsg("请输入反馈内容");
                } else {
                    EditText feedback_contact_edit =
                            (EditText) findViewById(R.id.feedback_contact_edit);
                    contact = feedback_contact_edit.getText().toString();
                    if (contact.equals("")) {
                        contact = MyAccountManager.getInstance(this).getUserId();
                    }

                    // 连网
                    controller.handle(0, "submit", content, contact);
                    showLoginDialog();
                }
                break;

        }
    }

    /** 底部提示框显示 */
    private void showLoginDialog() {
        if (mLoginDialog == null) {
            mLoginDialog = new ToastDialog(this);
            mLoginDialog.setDissmisOnClickOutSide(false);
        }
        mLoginDialog.loading("正在提交反馈");
    }

    /** 底部提示框隐藏 */
    private void hideLoginDailog() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                if (mLoginDialog != null) {
                    mLoginDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }


    
    private void onCommitFinish(boolean isSuccess){
        hideLoginDailog();
        if (isSuccess) {
            EditText feedback_content_edit = (EditText) findViewById(R.id.feedback_content_edit);
            feedback_content_edit.setText("");
        }
        showMsg(message);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
